﻿using ByteSite.API.Model;
using ByteSite.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;

namespace ByteSite.API.Controllers
{
    [RoutePrefix("api/product")]
    public class ProductController : ApiController
    {
        protected internal Entitys.sysconfig sysConfig;
        public ProductController()
        {
            sysConfig = new BLL.sysconfig().loadConfig();
        }

        [HttpPost]
        [Route("get_pools")]
        public HttpResponseMessage get_pools()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象

            GetPoolsRequest req = DTRequest.RequestFormParams<GetPoolsRequest>(request);
            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(req));

            List<QLYCCategoryModel> list = new List<QLYCCategoryModel>();
            BLL.article_category bll = new BLL.article_category();
            List<Entitys.dt_article_category> categories = bll.GetList(0, "goods");
            foreach (Entitys.dt_article_category c in categories)
            {
                QLYCCategoryModel qlc = new QLYCCategoryModel();

                qlc.id = Utils.ObjToInt(c.call_index) == 0 ? c.id : Utils.ObjToInt(c.call_index);
                qlc.name = c.title;
                list.Add(qlc);

            }


            AccessTokenResponse resp = new AccessTokenResponse();
            resp.success = true;
            resp.result = list;


            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(resp));
            var result = new HttpResponseMessage()
            {
                Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
            };
            return result;
        }


        [HttpPost]
        [Route("skus")]
        public HttpResponseMessage skus()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象

            SkusRequest req = DTRequest.RequestFormParams<SkusRequest>(request);
            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(req));
            BaseResponse resp = new BaseResponse();
            if (string.IsNullOrEmpty(req.catalog_id))
            {
                resp.success = false;
                resp.desc = "catalog_id is null";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }
            List<string> skus = new List<string>();
            BLL.article bll = new BLL.article();
            BLL.article_category categoryBLL = new BLL.article_category();
            Entitys.dt_article_category categoryModel = categoryBLL.GetModelCall(req.catalog_id.ToString());

            List<Entitys.article> articles = bll.ArticleList("goods", 10000, "status=0 and category_id='"+ categoryModel.id + "'", "id desc");
            foreach (Entitys.article a in articles)
            {
                skus.Add(a.id.ToString());

            }

            resp.success = true;
            resp.result = skus;


            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(resp));
            var result = new HttpResponseMessage()
            {
                Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
            };
            return result;
        }


        [HttpPost]
        [Route("detail")]
        public HttpResponseMessage detail()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象

            DetailRequest req = DTRequest.RequestFormParams<DetailRequest>(request);
            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(req));
            BaseResponse resp = new BaseResponse();
            if (string.IsNullOrEmpty(req.sku))
            {
                resp.success = false;
                resp.desc = "sku is null";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }

            if (Utils.StrToInt(req.sku, 0) == 0)
            {
                resp.success = false;
                resp.desc = "sku is error";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }


            BLL.article bll = new BLL.article();
            Entitys.article article = bll.GetModel(2, Utils.StrToInt(req.sku, 0));
            DetailResponse detail = new DetailResponse();

            detail.sku = article.id.ToString();
            detail.url = sysConfig.weburl + "/goods/show-" + article.id + ".aspx";
            detail.model = article.fields["model"].ToStr();
            detail.weight = article.fields["weight"].ToStr();
            detail.image_path = article.img_url.StartsWith("http") ? article.img_url : sysConfig.weburl + (article.img_url.StartsWith("/") ? article.img_url : "/" + article.img_url);
            detail.state = (1 - article.status).ToStr();
            detail.brand_name = article.fields["brand_name"].ToStr();
            detail.name = article.title;
            detail.product_area = article.fields["product_area"].ToStr();
            detail.upc = article.fields["upc"].ToString();
            detail.unit = article.fields["unit"].ToString();
            detail.category = new BLL.article_category().GetModel(article.category_id).call_index.ToString();
            detail.service = article.fields["service"].ToStr();
            detail.code_69 = article.fields["code_69"].ToStr();
            detail.attributes = "";
            string _content = article.content;
            string[] imgs = Utils.GetHtmlImageUrlList(article.content);
            if (imgs.Length > 0)
            {
                foreach (string img in imgs)
                {
                    if (img.StartsNotWith("http"))
                    {
                        _content = _content.Replace(img, sysConfig.weburl + (img.StartsWith("/") ? img : "/" + img));
                    }
                }
            }
            detail.introduction = _content;



            detail.param = article.fields["param"].ToStr().Replace("\"","'");
            detail.ware = article.fields["ware"].ToStr();
            detail.sale_actives = article.is_slide;

            detail.@case = article.fields["case"].ToStr();
            detail.goods_number = article.fields["goods_number"].ToStr();
            detail.goods_date = article.fields["goods_date"].ToStr();
            detail.purity = article.fields["purity"].ToStr();

            resp.success = true;
            resp.result = detail;


            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(resp));
            var result = new HttpResponseMessage()
            {
                Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
            };
            return result;
        }


        [HttpPost]
        [Route("shelf_states")]
        public HttpResponseMessage shelf_states()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象

            ShelfStatesRequest req = DTRequest.RequestFormParams<ShelfStatesRequest>(request);
            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(req));
            BaseResponse resp = new BaseResponse();
            if (string.IsNullOrEmpty(req.sku))
            {
                resp.success = false;
                resp.desc = "sku is null";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }

            string[] skus = Utils.SplitString(req.sku, ",");
            string _skus = "";
            foreach (string sku in skus)
            {
                _skus += sku + ",";
            }
            _skus = _skus.TrimEnd(',');


            List<ShelfStatesResponse> list = new List<ShelfStatesResponse>();
            BLL.article bll = new BLL.article();
            List<Entitys.article> articles = bll.ArticleList("goods", 10000, "id in (" + _skus + ")", "id desc");
            foreach (Entitys.article a in articles)
            {
                list.Add(new ShelfStatesResponse { sku = a.id.ToString(), state = a.status });
            }

            resp.success = true;
            resp.result = list;


            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(resp));
            var result = new HttpResponseMessage()
            {
                Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
            };
            return result;
        }


        [HttpPost]
        [Route("images")]
        public HttpResponseMessage images()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象

            ImagesRequest req = DTRequest.RequestFormParams<ImagesRequest>(request);
            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(req));
            BaseResponse resp = new BaseResponse();
            if (string.IsNullOrEmpty(req.sku))
            {
                resp.success = false;
                resp.desc = "sku is null";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }

            string[] skus = Utils.SplitString(req.sku, ",");
            string _skus = "";
            foreach (string sku in skus)
            {
                _skus += sku + ",";
            }
            _skus = _skus.TrimEnd(',');


            List<ImagesResponse> list = new List<ImagesResponse>();
            BLL.article bll = new BLL.article();
            List<Entitys.article> articles = bll.ArticleFullList("goods", 10000, "id in (" + _skus + ")", "id desc");
            foreach (Entitys.article a in articles)
            {
                ImagesResponse model = new ImagesResponse();
                model.sku = a.id.ToString();
                model.images = new List<ImagesOrder>();
                if (a.albums != null && a.albums.Count > 0)
                {
                    foreach (Entitys.dt_article_albums img in a.albums.OrderBy(x => x.sort_id))
                    {
                        model.images.Add(new ImagesOrder { path = (img.original_path.StartsNotWith("http") ? sysConfig.weburl + img.original_path : img.original_path), order = Utils.ObjToInt(img.sort_id, 99) });
                    }
                }
                list.Add(model);
            }

            resp.success = true;
            resp.result = list;


            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(resp));
            var result = new HttpResponseMessage()
            {
                Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
            };
            return result;
        }


        [HttpPost]
        [Route("prices")]
        public HttpResponseMessage prices()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象

            PricesRequest req = DTRequest.RequestFormParams<PricesRequest>(request);
            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(req));
            BaseResponse resp = new BaseResponse();
            if (string.IsNullOrEmpty(req.sku))
            {
                resp.success = false;
                resp.desc = "sku is null";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }

            string[] skus = Utils.SplitString(req.sku, ",");
            string _skus = "";
            foreach (string sku in skus)
            {
                _skus += sku + ",";
            }
            _skus = _skus.TrimEnd(',');


            List<PricesResponse> list = new List<PricesResponse>();
            BLL.article bll = new BLL.article();
            List<Entitys.article> articles = bll.ArticleFullList("goods", 10000, "id in (" + _skus + ")", "id desc");
            foreach (Entitys.article a in articles)
            {
                list.Add(new PricesResponse { sku = a.id.ToString(), price = a.fields["sell_price"].ToString(), mall_price = a.fields["market_price"].ToString() });
            }

            resp.success = true;
            resp.result = list;


            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(resp));
            var result = new HttpResponseMessage()
            {
                Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
            };
            return result;
        }


        [HttpPost]
        [Route("ratings")]
        public HttpResponseMessage ratings()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象

            RatingsRequest req = DTRequest.RequestFormParams<RatingsRequest>(request);
            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(req));
            BaseResponse resp = new BaseResponse();
            if (string.IsNullOrEmpty(req.sku))
            {
                resp.success = false;
                resp.desc = "sku is null";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }

            string[] skus = Utils.SplitString(req.sku, ",");
            string _skus = "";
            foreach (string sku in skus)
            {
                _skus += sku + ",";
            }
            _skus = _skus.TrimEnd(',');


            List<RatingsResponse> list = new List<RatingsResponse>();
            BLL.article bll = new BLL.article();
            List<Entitys.article> articles = bll.ArticleFullList("goods", 10000, "id in (" + _skus + ")", "id desc");
            foreach (Entitys.article a in articles)
            {
                list.Add(new RatingsResponse { sku = a.id.ToString(), average = 5, medium = 0m, good = 1.0m, bad = 0m });
            }

            resp.success = true;
            resp.result = list;


            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(resp));
            var result = new HttpResponseMessage()
            {
                Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
            };
            return result;
        }


        [HttpPost]
        [Route("stocks")]
        public HttpResponseMessage stocks()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象

            StocksRequest req = DTRequest.RequestFormParams<StocksRequest>(request);
            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(req));
            BaseResponse resp = new BaseResponse();
            if (string.IsNullOrEmpty(req.sku))
            {
                resp.success = false;
                resp.desc = "sku is null";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }

            string[] skus = Utils.SplitString(req.sku, ",");
            string _skus = "";
            foreach (string sku in skus)
            {
                _skus += sku + ",";
            }
            _skus = _skus.TrimEnd(',');


            List<StocksResponse> list = new List<StocksResponse>();
            BLL.article bll = new BLL.article();
            List<Entitys.article> articles = bll.ArticleFullList("goods", 10000, "id in (" + _skus + ")", "id desc");
            foreach (Entitys.article a in articles)
            {
                list.Add(new StocksResponse { area = "1_0_0", desc = (Utils.ObjToInt(a.fields["stock_quantity"], 0) > 0 ? "有货" : "无货"), sku = a.id.ToString(), num = Utils.ObjToInt(a.fields["stock_quantity"], 0) });
            }

            resp.success = true;
            resp.result = list;


            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(resp));
            var result = new HttpResponseMessage()
            {
                Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
            };
            return result;
        }


        [HttpPost]
        [Route("certificates")]
        public HttpResponseMessage certificates()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象

            ImagesRequest req = DTRequest.RequestFormParams<ImagesRequest>(request);
            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(req));
            BaseResponse resp = new BaseResponse();
            if (string.IsNullOrEmpty(req.sku))
            {
                resp.success = false;
                resp.desc = "sku is null";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }

            string[] skus = Utils.SplitString(req.sku, ",");
            string _skus = "";
            foreach (string sku in skus)
            {
                _skus += sku + ",";
            }
            _skus = _skus.TrimEnd(',');


            List<CertificatesResponse> list = new List<CertificatesResponse>();
            BLL.article bll = new BLL.article();
            List<Entitys.article> articles = bll.ArticleFullList("goods", 10000, "id in (" + _skus + ")", "id desc");
            foreach (Entitys.article a in articles)
            {
                CertificatesResponse model = new CertificatesResponse();
                model.sku = a.id.ToString();

                model.save_energy_cert_no = Utils.ObjectToStr(a.fields["save_energy_cert_no"]);
                model.save_energy_cert_image = Utils.ObjectToStr(a.fields["save_energy_cert_image"]).IsNullOrEmpty() ? "" : (Utils.ObjectToStr(a.fields["save_energy_cert_image"]).StartsNotWith("http") ? sysConfig.weburl + Utils.ObjectToStr(a.fields["save_energy_cert_image"]) : Utils.ObjectToStr(a.fields["save_energy_cert_image"]));
                model.save_energy_cert_indate = Utils.ObjectToDateTime(a.fields["save_energy_cert_indate"], DateTime.Parse("1900-01-01 00:00:00")).ToString("yyyy-MM-dd")== "1900-01-01"?"": Utils.ObjectToDateTime(a.fields["save_energy_cert_indate"], DateTime.Parse("1900-01-01 00:00:00")).ToString("yyyy-MM-dd");

                model.environment_protect_cert_no = Utils.ObjectToStr(a.fields["environment_protect_cert_no"]);
                model.environment_protect_cert_image = Utils.ObjectToStr(a.fields["environment_protect_cert_image"]).IsNullOrEmpty() ? "" : (Utils.ObjectToStr(a.fields["environment_protect_cert_image"]).StartsNotWith("http") ? sysConfig.weburl + Utils.ObjectToStr(a.fields["environment_protect_cert_image"]) : Utils.ObjectToStr(a.fields["environment_protect_cert_image"]));
                model.environment_protect_cert_indate = Utils.ObjectToDateTime(a.fields["environment_protect_cert_indate"], DateTime.Parse("1900-01-01 00:00:00")).ToString("yyyy-MM-dd") == "1900-01-01" ? "" : Utils.ObjectToDateTime(a.fields["environment_protect_cert_indate"], DateTime.Parse("1900-01-01 00:00:00")).ToString("yyyy-MM-dd");
                list.Add(model);

            }

            resp.success = true;
            resp.result = list;


            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(resp));
            var result = new HttpResponseMessage()
            {
                Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
            };
            return result;
        }


    }
}